package com.bonc.ioc.util;


import org.apache.kerby.util.Hex;

import java.security.MessageDigest;
import java.util.Random;

/**
 * @author ：liyy
 * @date ：Created in 2020/3/24 17:25
 * @description：
 * @modified By：
 * @version: V1.0
 */
public class PasswordEncryptor {

    /**
     * 生成含有随机盐的密码
     */
    public static String generate(String password) {
        //第一个随机数
        int i1 = new Random().nextInt(99999999);
        //第二个随机数
        int i2 = new Random().nextInt(99999999);
        //生成盐
        String salt = String.valueOf(i1) + String.valueOf(i2);
        int saltMaxLength = 16;
        if (salt.length() < saltMaxLength) {
            for (int i = 0; i < saltMaxLength - salt.length(); i++) {
                salt += "0";
            }
        }
        password = md5Hex(password + salt);
        char[] cs1 = password.toCharArray();
        char[] cs2 = salt.toCharArray();
        char[] cs = new char[48];
        int passwordLenth = 48;
        int loop = 3;
        for (int i = 0; i < passwordLenth; i += loop) {
            cs[i] = cs1[i / 3 * 2];
            cs[i + 1] = cs2[i / 3];
            cs[i + 2] = cs1[i / 3 * 2 + 1];
        }
        return new String(cs);
    }

    /**
     * 校验密码是否正确
     */

    /**
     * 验证密码是否正确
     *
     * @param password 原始密码
     * @param md5      加密后的密码
     * @return
     */
    public static boolean verify(String password, String md5) {
        char[] cs = md5.toCharArray();
        char[] cs1 = new char[32];
        char[] cs2 = new char[16];
        int passwordLenth = 48;
        int loop = 3;
        for (int i = 0; i < passwordLenth; i += loop) {
            cs1[i / 3 * 2] = cs[i];
            cs1[i / 3 * 2 + 1] = cs[i + 2];
            cs2[i / 3] = cs[i + 1];
        }
        String salt = new String(cs2);
        return md5Hex(password + salt).equals(new String(cs1));
    }

    /**
     * 获取十六进制字符串形式的MD5摘要
     */
    public static String md5Hex(String src) {
        try {
            //获取md5的一个加密
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(src.getBytes());
            return new String(Hex.encode(bs));
        } catch (Exception e) {
            return null;
        }
    }

}
